package com.team407.cheyoubang.net;

import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.team407.cheyoubang.down.DownInfo;

import android.util.Log;


public class Request {
	public String doPost(String url,Map<String, String> map, String encoding) throws ClientProtocolException, IOException{
		String json = "";
		HttpPost httpPost = new HttpPost(url);
		Iterator<String> iterator = map.keySet().iterator();
		List<NameValuePair> pairs = new ArrayList<NameValuePair>();
		while (iterator.hasNext()) {
			
			String key = iterator.next();
			String value = map.get(key);
			BasicNameValuePair nameValuePair = new BasicNameValuePair(key, value);
			pairs.add(nameValuePair);
		}
		if(pairs.size() != 0){
			httpPost.setEntity(new UrlEncodedFormEntity(pairs, encoding));
		}
		HttpClient httpClient = new DefaultHttpClient();
		HttpResponse response = httpClient.execute(httpPost);
		if (response.getStatusLine().getStatusCode() == 200) { 
			// 第三步，使用getEntity方法活得返回结果 
			json = EntityUtils.toString(response.getEntity()); 
        } else{
        	Log.e(Request.class.getName(), "网络请求失败！");
        	return null;
        }
		Log.i(Request.class.getName(), "结果：" + json);
		return json;
	}
	/**
	 * 请求数据为json
	 * @param url
	 * @param json
	 * @param encoding
	 * @return
	 * @throws ParseException
	 * @throws IOException
	 */
	public String doJsonPost(String url, String json, String encoding) throws ParseException, IOException{
		String resultJson = "";
		HttpPost httpPost = new HttpPost(url);
		StringEntity entity = new StringEntity(json, encoding);
		httpPost.setEntity(entity);
		HttpClient httpClient = new DefaultHttpClient();
		HttpResponse response = httpClient.execute(httpPost);
		if (response.getStatusLine().getStatusCode() == 200) { 
			// 第三步，使用getEntity方法活得返回结果  
			resultJson = EntityUtils.toString(response.getEntity()); 
        } else{
        	Log.e(Request.class.getName(), "网络请求失败！");
        	return null;
        }
		Log.i(Request.class.getName(), "结果：" + resultJson);
		return resultJson;
	}
	
	public void down(DownInfo downInfo){
		try {
			downInfo.isPause = false;
			URL url = new URL(downInfo.url);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setRequestMethod("GET");
			connection.setConnectTimeout(30000);
			//connection.setRequestProperty("Range", "bytes=" + downInfo.stPos + "-");
			connection.connect();
			if(connection.getResponseCode() == 200){
				downInfo.totalSize = connection.getContentLength();
				downInfo.prepare();
				
				RandomAccessFile fileSave = new RandomAccessFile(downInfo.filePath, "rwd");
				fileSave.seek(downInfo.stPos);
				
				InputStream inputStream = connection.getInputStream();
				byte[] buffer = new byte[1024];
				int len = 0;
				while((len = inputStream.read(buffer)) > 0 && !downInfo.isPause){
					fileSave.write(buffer, 0, len);
					downInfo.curPos = downInfo.curPos + len;
					downInfo.updateProgress();
				}
				
				inputStream.close();
				fileSave.close();
				downInfo.finlish();
				
			}else{
				downInfo.error();
			}
			
		} catch (MalformedURLException e) {
			downInfo.error();
			e.printStackTrace();
		} catch (IOException e) {
			downInfo.error();
			e.printStackTrace();
		}
	}
}
